package net.roostertech.bta2dpfixer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DeviceDAO {
	DeviceSQLiteHelper dbHelper;
	private final String LOGTAG = "BTFixer";

	private String[] allColumns = { DeviceSQLiteHelper.COLUMN_ID,
			DeviceSQLiteHelper.COLUMN_DEVICE_NAME };
	
	private DeviceDAO(Context context) {
		dbHelper = new DeviceSQLiteHelper(context);
	}
	
	private static DeviceDAO dao = null;
	
	public static DeviceDAO getInstance(Context context) {
		if (dao != null) {
			return dao;
		} else {
			dao = new DeviceDAO(context);
			return dao;
		}
	}

	public boolean isA2DP(String deviceName) {
		boolean ret = false;
		SQLiteDatabase db;
		Cursor cursor;
		
		String [] columns = new String [] {DeviceSQLiteHelper.COLUMN_DEVICE_NAME};
		String selection = DeviceSQLiteHelper.COLUMN_DEVICE_NAME+ "= \'" + deviceName + "\'";
		db = dbHelper.getReadableDatabase();
		cursor = db.query(DeviceSQLiteHelper.DEVICES_TBL, columns, selection, null, null, null, null);
		
		if (cursor.getCount() > 0) {
			ret = true;
		}
		
		cursor.close();
		return ret;
	}

	/* Insert device name into table to mark that it is A2DP capable */
	public void markA2DP(String deviceName) {
		
		SQLiteDatabase db;
		db = dbHelper.getWritableDatabase();
		ContentValues vals = new ContentValues();
		vals.put(DeviceSQLiteHelper.COLUMN_DEVICE_NAME, deviceName);
		long row = db.insert(DeviceSQLiteHelper.DEVICES_TBL, null, vals);
		
		Log.i(LOGTAG, deviceName + " -> "  + row);
		
	}
	
	public void unmarkA2DP(String deviceName) {
		SQLiteDatabase db;
		db = dbHelper.getWritableDatabase();
		db.delete(DeviceSQLiteHelper.DEVICES_TBL, 
				DeviceSQLiteHelper.COLUMN_DEVICE_NAME+ " = \'" + deviceName+"\'", null);
	}
	
	
	public void dump() {
		SQLiteDatabase db;
		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(DeviceSQLiteHelper.DEVICES_TBL, null, null, null, null, null, null);
		
		Log.i(LOGTAG, "Count "  + cursor.getCount());

		if (!cursor.moveToFirst()) {
			return;
		}
		do {
			Log.i(LOGTAG, "id " + cursor.getInt(0) + " name " + cursor.getString(1));
		} while (cursor.moveToNext());
		
	}
	public void close() {
		dbHelper.close();
	}

}
